<template>
	<a-modal title="修改头像" :visible="visible" :maskClosable="false" :width="800" :footer="null" @cancel="cancelHandel" :afterClose="afterClose" :destroyOnClose="true">
		<a-spin :spinning="confirmLoading">
			<a-row>
				<a-col :xs="24" :md="12" :style="{ height: '350px' }">
					<vue-cropper
						ref="cropper"
						:img="options.img"
						:info="true"
						:autoCrop="options.autoCrop"
						:autoCropWidth="options.autoCropWidth"
						:autoCropHeight="options.autoCropHeight"
						:fixedBox="options.fixedBox"
						:outputType="options.outputType"
						@realTime="realTime"
					></vue-cropper>
				</a-col>
				<a-col :xs="24" :md="12" :style="{ height: '350px' }">
					<div class="avatar-upload-preview"><img :src="previews.url" :style="previews.img" /></div>
				</a-col>
			</a-row>
			<br />
			<a-row>
				<a-col :lg="2" :md="2">
					<a-upload name="file" accept="image/*" :beforeUpload="beforeUpload" :showUploadList="false"><a-button icon="upload">选择图片</a-button></a-upload>
				</a-col>
				<a-col :lg="{ span: 1, offset: 2 }" :md="2"><a-button icon="plus" @click="changeScale(1)" /></a-col>
				<a-col :lg="{ span: 1, offset: 1 }" :md="2"><a-button icon="minus" @click="changeScale(-1)" /></a-col>
				<a-col :lg="{ span: 1, offset: 1 }" :md="2"><a-button icon="undo" @click="rotateLeft" /></a-col>
				<a-col :lg="{ span: 1, offset: 1 }" :md="2"><a-button icon="redo" @click="rotateRight" /></a-col>
				<a-col :lg="{ span: 2, offset: 6 }" :md="2"><a-button type="primary" @click="finish()">保存</a-button></a-col>
			</a-row>
		</a-spin>
	</a-modal>
</template>
<script>
import { VueCropper } from 'vue-cropper';
import { postActionUpload } from '@/api/index.js';
//将base64转换为blob
function dataURLtoFile(dataURI, type) {
	let binary = atob(dataURI.split(',')[1]);
	let array = [];
	for (let i = 0; i < binary.length; i++) {
		array.push(binary.charCodeAt(i));
	}
	return new Blob([new Uint8Array(array)], { type: type });
}
function getBase64(file) {
	return new Promise((resolve, reject) => {
		const reader = new FileReader();
		reader.readAsDataURL(file);
		reader.onload = () => resolve(reader.result);
		reader.onerror = error => reject(error);
	});
}
export default {
	data() {
		return {
			visible: false,
			id: null,
			confirmLoading: false,
			fileList: [],
			uploading: false,
			options: {
				img: '',
				autoCrop: true,
				autoCropWidth: 200,
				autoCropHeight: 200,
				fixedBox: true,
				outputType: 'png'
			},
			previews: {},
			fileName: '',
			objectData: {}
		};
	},
	components: {
		VueCropper
	},
	methods: {
		edit(img) {
			this.confirmLoading = false;
			this.visible = true;
			// if (img) {
			// 	this.setAvatarBase64(img, base64 => {
			// 		this.options.img = base64;
			// 	});
			// }
		},
		// 设置头像base64
		setAvatarBase64(src, callback) {
			let _this = this;
			let image = new Image();
			// 支持跨域图片
			image.crossOrigin = '*';
			// 处理缓存
			image.src = src + '?v=' + Math.random();
			image.onload = function() {
				let base64 = _this.transBase64FromImage(image);
				callback && callback(base64);
			};
		},
		// 将网络图片转换成base64格式
		transBase64FromImage(image) {
			let canvas = document.createElement('canvas');
			canvas.width = image.width;
			canvas.height = image.height;
			let ctx = canvas.getContext('2d');
			ctx.drawImage(image, 0, 0, image.width, image.height);
			// 可选其他值 image/jpeg
			return canvas.toDataURL('image/png');
		},
		close() {
			this.visible = false;
		},
		cancelHandel() {
			this.close();
		},
		changeScale(num) {
			num = num || 1;
			this.$refs.cropper.changeScale(num);
		},
		rotateLeft() {
			this.$refs.cropper.rotateLeft();
		},
		rotateRight() {
			this.$refs.cropper.rotateRight();
		},
		afterClose() {
			this.options.img = '';
			this.previews = {};
		},
		beforeUpload(file) {
			const reader = new FileReader();
			// 把Array Buffer转化为blob 如果是base64不需要
			// 转化为base64
			reader.readAsDataURL(file);
			reader.onload = () => {
				this.options.img = reader.result;
			};
			return false;
		},
		// 上传图片（点击上传按钮）
		finish() {
			const vm = this;
			if (!vm.options.img) {
				vm.$message.error('请选择一张图片');
				return false;
			}
			let formData = new FormData(); //以表单的形式传递给oss
			vm.confirmLoading = true;
			this.$refs.cropper.getCropData(data => {
				this.modelSrc = data;
				/* 获取头像base64 */
				var imgdata = data.split(',')[1];
				var fileType = data.split(';')[0].split('/')[1];
				/* console.log('fileType', data.split(';')[0]); */
				let fileData = dataURLtoFile(data, data.split(';')[0]);
				let fileName = new Date().getTime() + 'avatar.' + fileType;
				let fileOfBlob = new File([fileData], fileName);
				formData.append('file', fileOfBlob);
				/* this.saveFile(fileOfBlob);
				return false;
				var param = {
					file: data,
					fileName: new Date().getTime() + 'avatar.png'
				};
				 this.$postAction(this.$api.uploadImg, param)*/
				postActionUpload(this.$api.uploadFile, formData)
					.then(da => {
						if (da.code == 1) {
							this.$message.success('上传个人头像成功');
							this.visible = false;
							this.$emit('uploadImg', da.data);
						}
					})
					.finally(() => {
						vm.confirmLoading = false;
						vm.close();
					});
			});
		},
		realTime(data) {
			this.previews = data;
		},
		async saveFile(file) {
			const _this = this;
			this.$getAction(this.$api.userHeadImg, {
				fileName: file.name
			}).then(res => {
				_this.objectData.OSSAccessKeyId = res.data.accessid; // Bucket拥有者的AccessKey ID。
				_this.objectData.policy = res.data.policy; //Policy规定了请求表单域的合法性。
				_this.objectData.Signature = res.data.signature; //根据AccessKey Secret和Policy计算的签名信息，OSS验证该签名信息从而验证该Post请求的合法性。
				_this.objectData.dir = res.data.dir; //前缀
				_this.objectData.host = res.data.host; // "https://" + bucketname + '.' + endpoint;  (前端请求oss服务路径)
				_this.objectData.key = res.data.key; //dir + fileName (上传Object的名称。)
				let param = {
					name: file.name,
					key: _this.objectData.key,
					policy: _this.objectData.policy,
					OSSAccessKeyId: _this.objectData.OSSAccessKeyId,
					success_action_status: '200', //必须这么写 不要问为什么
					signature: _this.objectData.Signature,
					file: file //一定在最后面
				};

				// console.log('_this.objectData.key',_this.objectData.key)
				_this.upload(_this.objectData.host, param, res.data.previewKey);
				// resolve(true);
			});
		},
		async upload(url, param, previewKey) {
			const formData = new FormData(); //以表单的形式传递给oss
			Object.keys(param).forEach(key => {
				formData.append(key, param[key]);
			});
			let previewUrl = await getBase64(param.file);
			postActionUpload(url, formData)
				.then(res => {
					this.$message.success('上传个人头像成功');
					this.visible = false;
					this.$emit('uploadImg', param.key, previewKey);
				})
				.finally(() => {
					this.confirmLoading = false;
				});
		}
	}
};
</script>

<style lang="less" scoped>
.avatar-upload-preview {
	position: absolute;
	top: 50%;
	transform: translate(50%, -50%);
	width: 200px;
	height: 200px;
	border-radius: 50%;
	box-shadow: 0 0 4px #ccc;
	overflow: hidden;

	img {
		width: 100%;
		height: 100%;
	}
}
</style>
